package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.FixedKeySet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;


    // 查询
    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    //  文件上传
    @Override
    public String uploadBpmnfile(MultipartFile file) throws IOException {
        // 判断格式必须为 bpmn 格式文件
        String ext = FileUploadUtils.getExtension(file); //获取后缀
        if (!"bpmn".equals(ext)){ //如果后缀名不为bpmn,就抛异常
            throw  new BusinessException("格式要为bpmn文件");
        }

        String path = FileUploadUtils.upload(SystemConfig.getProfile(), file);

        return path;
    }

    //流程文件部署
    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws IOException {
        // 1.根据path 找到磁盘中的文件
        File file = new File(SystemConfig.getProfile(), path);

        // 2.调用activiti 的api 进行部署操作
        FileInputStream fileInputStream = new FileInputStream(file);
        Deployment deployment = repositoryService.createDeployment().addInputStream(path,fileInputStream).deploy();

        // 查询流程定义信息
        fileInputStream.close();

        ProcessDefinition processDefinition = repositoryService.
                createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();

        // 3. 把流程图信息保存到bpmnInfo 一份
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setInfo(info);
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setDeployTime(deployment.getDeploymentTime());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfoMapper.insert(bpmnInfo);

    }

    // 删除流程定义
    @Override
    public void delete(Long id) {
        // 1.先查询出来一条流程定义
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        // 再删除bpmnInfo 信息
        bpmnInfoMapper.deleteByPrimaryKey(id);

        // 2.删除activiti 中流程定义信息
        /**
         * 在删除流程定义 要考虑服务单项状态问题
         * 可以 先查询流程定义下流程实例 -> 通过流程实例找到 businesskey -> 通过businesskey 最终把数据修改成初始化状态
         */

        // 查询出来流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(bpmnInfo.getDeploymentId()).singleResult();
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId());

        // 3.删除部署文件
        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        if (file.exists()){
            file.delete();
        }

    }

    // 流程文件查看
    @Override
    public InputStream readResource(String deploymentId, String type) {
        InputStream inputStream = null;
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(deploymentId).singleResult();
        if ("xml".equals(type)){
            // 响应xmnl
            inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        }else{
            // 响应png
            /**
             * 第一个参数: BpmnModel
             * 第二个参数: 高亮节点集合
             * 第三个参数: 高亮连线集合
             */
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            inputStream = generator.generateDiagram(repositoryService.getBpmnModel(processDefinition.getId()),
                    Collections.emptyList(),
                    Collections.emptyList(), "宋体", "宋体", "宋体");
        }

        return inputStream;
    }

    @Override
    public List<BpmnInfo> queryByType(String type) {
        return bpmnInfoMapper.queryByType(type);
    }


}












